package niuke.week02;

import java.util.Scanner;

/**
 给定一棵搜索二叉树后序遍历的结果，其中没有重复值，生成整棵树并返回。
 搜索二叉树：任一子树中所有左子树的节点编号小于根节点，右子树的节点编号大于根节点
 */
public class GenTree {

    static class Node{
        int val;
        Node left;
        Node right;

        public Node(int val) {
            this.val = val;
        }
    }

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt();
        int []arr = new int[n];
        for (int i = 0; i < n; i++)
            arr[i] = sc.nextInt();

        int []res = new int[n];
        Node root = gen( res,arr, 0, arr.length - 1);
        for (int re : res) {
            System.out.print(re+" ");
        }
//        inOrder(root);
    }

    private static  Node gen(int []res,int[]a,int l,int r){//生成arr[i...j]
        if(l>r){
            return null;
        }
        if(l==r){
            return new Node(a[l]);
        }

        int m = r;
//        System.out.println(m);
        while (m>=0 && a[m]>=a[r]){//找到左树与右树的交界处
            m--;
        }

        Node head = new Node(a[r]);//根节点

        Node leftNode = gen(res, a, l, m);//左树的根节点
        if(leftNode!=null){
            res[leftNode.val-1] = head.val;//指定父节点
            head.left = leftNode;
        }

        Node rightNode = gen(res ,a, m + 1, r - 1);//右树的根节点
        if(rightNode!=null){
            res[rightNode.val-1] = head.val;
            head.right = rightNode;
        }
        return head;
    }


    public  static void inOrder(Node node){
        if (node==null)
            return;
        inOrder(node.left);
        System.out.print(node.val+" ");
        inOrder(node.right);
    }
}